#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Q1mi"
# Date: 2018/10/24

import pymssql
import pandas as pd
from datetime import timedelta
import time
import matplotlib.pyplot as plt
from dingtalkchatbot.chatbot import DingtalkChatbot
import math
import numpy as np
import random

################工具######################



#################一元一次################

def linefit(x , y):
    N = float(len(x))
    sx,sy,sxx,syy,sxy=0,0,0,0,0
    for i in range(0,int(N)):
        sx  += x[i]
        sy  += y[i]
        sxx += x[i]*x[i]
        syy += y[i]*y[i]
        sxy += x[i]*y[i]
    a = (sy*sx/N -sxy)/( sx*sx/N -sxx)
    b = (sy - a*sx)/N
    r = abs(sy*sx/N-sxy)/math.sqrt((sxx-sx*sx/N)*(syy-sy*sy/N))
    return a,b,r


###################一元二次####################
def f(x):
    return x ** 2 + 1


def f_fit(x, y_fit):
    x = np.array(x)
    a, b, c = y_fit.tolist()
    return a * x ** 2 + b * x + c


############天气数据整合分析#################
def weater_rule(weater_data, day):
    '''
    :param weater_data: 未来day天的天气数据和前一天的天气数据
    :return: 气象规则
    '''
    #############2、气象规则###########################
    # 1.1、特殊天气  暴雨/雷阵雨/大雨--ts_weater_gz
    ts_weater = ['暴雨', '雷阵雨', '大雨', '雪']
    ts_weater_data = []

    # 1.2、主要以什么天气为主--main_weater
    stnm = weater_data['STNM'].unique().tolist()
    main_weater_data = []
    ##温度波动
    weater_flu_low_data = []##与前一日对比降温大于3度
    weater_flu_up_data = []#与前一日对比升温大于3度
    weater_flu_0_data = []
    weater_flu_1_data = []
    weater_flu_2_data = []
    weater_flu_low_gz_time = []  # 骤降的日期
    weater_flu_up_gz_time = []  # 骤升的日期
    wd_cut_gz_time = []  # 日均温差的日期
    wd_cut_data = []
    lr_xl = [] #最高温的斜率
    lr_xl_min= []#最低温的斜率
    original_data = pd.DataFrame()

    for st in stnm:
        st_weater = weater_data[weater_data['STNM'] == st]
        main_weater = st_weater['weater'].value_counts().index[0]
        main_weater_data.append(main_weater)

        # 2.1、温度波动flu_low_gz===第二天和第一天的低温温度差值<= -3或者>=3  大于0，小于0========
        df1 = st_weater.iloc[:-1, :].reset_index().iloc[:, 1:]
        df2 = st_weater.iloc[1:, :].reset_index().iloc[:, 1:]

        df2.columns = df2.columns.map(lambda x: x + '_1')
        weater_all_data1 = pd.concat([df1,df2], axis=1)#, ignore_index=True

        high_next = st_weater['wd_max'][1:]
        high_now = st_weater['wd_max'][:-1]

        min_next = st_weater['wd_min'][1:]
        min_now = st_weater['wd_min'][:-1]

        weater_flu = st_weater.iloc[1:, :]

        weater_flu['flu_max'] = [int(int(x[0]) - int(x[1])) for x in zip(high_next, high_now)]
        weater_flu['flu_low'] = [int(int(x[0]) - int(x[1]))  for x in zip(min_next, min_now)]

        weater_flu['weater_flu_low'] = weater_flu.flu_max.apply(lambda x: 1 if x <= -3 else 0)
        weater_flu['weater_flu_up'] = weater_flu.flu_max.apply(lambda x: 1 if x >= 3 else 0)

        weater_flu_low = sum(weater_flu['weater_flu_low'])
        weater_flu_up = sum(weater_flu['weater_flu_up'])
        weater_flu_0 = sum(weater_flu.flu_max.apply(lambda x: 1 if x == 0 else 0))
        weater_flu_1 = sum(weater_flu.flu_max.apply(lambda x: 1 if x > 0 else 0))
        weater_flu_2 = sum(weater_flu.flu_max.apply(lambda x: 1 if x < 0 else 0))

        # 4.1 特殊天气
        weate = weater_flu['weater'].tolist()
        ts_weater_1 = ''
        for ts in ts_weater:
            for tt in weate:
                if ts in tt:
                    ts_weater_1 += ts

        ##5.1 日均温差
        weater_flu['wd_cut'] = weater_flu['wd_max'] - weater_flu['wd_min']
        weater_flu['wd_cut_gz'] = weater_flu.wd_cut.apply(lambda x: 1 if x >= 7 else 0)

        wd_cut_gz = sum(weater_flu['wd_cut_gz'])

        ##日期保存
        weater_flu_low_time1 = ','.join(weater_flu[weater_flu['weater_flu_low'] == 1]['YBTM'].apply(
            lambda x: x.strftime("%m-%d:")).tolist())  # %Y-%m-%d
        weater_flu_up_time2 = ','.join(weater_flu[weater_flu['weater_flu_up'] == 1]['YBTM'].apply(
            lambda x: x.strftime("%m-%d:")).tolist())  # %Y-%m-%d
        weater_flu_low_time1 = weater_flu_low_time1.replace('-','月').replace(':','日')
        weater_flu_up_time2 = weater_flu_up_time2.replace('-','月').replace(':','日')


        wd_cut_gz_time1 = '至'.join(
            [min(weater_flu[weater_flu['wd_cut_gz'] == 1]['YBTM'].apply(lambda x: x.strftime("%m{m}%d{d}".format(m='-',d=':'))).tolist()),
             max(weater_flu[weater_flu['wd_cut_gz'] == 1]['YBTM'].apply(lambda x: x.strftime("%m{m}%d{d}".format(m='-',d=':'))).tolist())]
            )  # %Y-%m-%d  nt.strftime('%Y{y}%m{m}%d{d}').format(y='年', m='月', d='日'))
        wd_cut_gz_time1 = wd_cut_gz_time1.replace('-','月').replace(':','日')

        ##一元一次
        a_min, b, r = linefit(range(len(weater_flu)), weater_flu['wd_min'].tolist())
        test_y = [a_min * x + b for x in range(len(weater_flu))]

        a_max, b1, r1 = linefit(range(len(weater_flu)), weater_flu['wd_max'].tolist())
        test_y_max = [a_max * x + b1 for x in range(len(weater_flu))]


        original_data = pd.concat([original_data,weater_flu],ignore_index=True)
        ts_weater_data.append(ts_weater_1)
        weater_flu_low_data.append(weater_flu_low)
        weater_flu_up_data.append(weater_flu_up)
        weater_flu_0_data.append(weater_flu_0)
        weater_flu_1_data.append(weater_flu_1)
        weater_flu_2_data.append(weater_flu_2)
        weater_flu_low_gz_time.append(weater_flu_low_time1)
        weater_flu_up_gz_time.append(weater_flu_up_time2)
        wd_cut_gz_time.append(wd_cut_gz_time1)
        wd_cut_data.append(wd_cut_gz)
        lr_xl.append(a_max)
        lr_xl_min.append(a_min)
        #####二元一次方程
        x = list(range(len(weater_flu)))
        y = weater_flu['wd_max'].tolist()
        y_fit = np.polyfit(x, y, 2)  # 二次多项式拟合
        y_show = np.poly1d(y_fit)  # 函数优美的形式
        a, b, c = y_fit.tolist()
        y1 = f_fit(x, y_fit)

        #print(y_show)  # 打印

        if a > 0:
            min_y = int(np.argwhere(y1 == min(y1)))

            print(x[min_y])

            ##画图
        x_show =  weater_flu['YBTM']#range(len(weater_flu))
        # 指定x轴展示角度
        plt.xticks(rotation=45)
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.plot(x_show, weater_flu['wd_min'], 'bo-', label="最高温")  # 蓝色--较好
        plt.plot(x_show, weater_flu['wd_max'], 'ro-', label="最低温")  # 红色
        #plt.plot(x_show, weater_flu['flu_max'], 'ro-', label="最低温")  # 红色
        plt.plot(x_show, test_y, 'y', label="趋势")
        plt.plot(x_show, test_y_max, 'y', label="趋势")
        plt.legend()  # 显示图中的标签
        plt.xlabel("时间")
        plt.ylabel('温度')
        plt.title('斜率，{}'.format(a))
        plt.show()

    weater_dic = {'STNM': stnm, 'main_weater': main_weater_data, 'ts_weater_gz': ts_weater_data,
                  'weater_flu_low_gz': weater_flu_low_data,
                  'weater_flu_up_gz': weater_flu_up_data, 'weater_flu_0_gz': weater_flu_0_data,
                  'weater_flu_1_gz': weater_flu_1_data, 'weater_flu_2_gz': weater_flu_2_data,
                  'weater_flu_low_gz_time': weater_flu_low_gz_time, 'weater_flu_up_gz_time': weater_flu_up_gz_time,
                  'wd_cut_gz_time': wd_cut_gz_time,'wd_cut_gz':wd_cut_data,'lr_xl':lr_xl,'lr_xl_min':lr_xl_min}


    pd_main_weater_data = pd.DataFrame(weater_dic)



    return pd_main_weater_data,original_data
